import React from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import { useDispatch } from 'react-redux';
import { AppDispatch } from '../store';
import { createVersion } from '../store/versionsSlice';
import {
  Box,
  Card,
  CardContent,
  TextField,
  Button,
  Typography,
  Grid,
} from '@mui/material';
import { useFormik } from 'formik';
import * as yup from 'yup';

const validationSchema = yup.object({
  version_number: yup.string()
    .required('Version number is required')
    .matches(/^\d+\.\d+\.\d+$/, 'Version must be in format X.Y.Z'),
});

const CreateVersion: React.FC = () => {
  const { projectId } = useParams<{ projectId: string }>();
  const navigate = useNavigate();
  const dispatch = useDispatch<AppDispatch>();

  const formik = useFormik({
    initialValues: {
      version_number: '',
      release_notes: '',
    },
    validationSchema,
    onSubmit: async (values) => {
      try {
        await dispatch(createVersion({
          project_id: Number(projectId),
          ...values,
        })).unwrap();
        navigate(`/projects/${projectId}`);
      } catch (error) {
        console.error('Failed to create version:', error);
      }
    },
  });

  return (
    <Box>
      <Typography variant="h4" gutterBottom>
        Create New Version
      </Typography>
      <Card>
        <CardContent>
          <form onSubmit={formik.handleSubmit}>
            <Grid container spacing={3}>
              <Grid item xs={12}>
                <TextField
                  fullWidth
                  id="version_number"
                  name="version_number"
                  label="Version Number"
                  placeholder="1.0.0"
                  value={formik.values.version_number}
                  onChange={formik.handleChange}
                  error={formik.touched.version_number && Boolean(formik.errors.version_number)}
                  helperText={formik.touched.version_number && formik.errors.version_number}
                />
              </Grid>
              <Grid item xs={12}>
                <TextField
                  fullWidth
                  id="release_notes"
                  name="release_notes"
                  label="Release Notes"
                  multiline
                  rows={4}
                  value={formik.values.release_notes}
                  onChange={formik.handleChange}
                />
              </Grid>
              <Grid item xs={12}>
                <Box display="flex" justifyContent="flex-end" gap={2}>
                  <Button
                    variant="outlined"
                    onClick={() => navigate(`/projects/${projectId}`)}
                  >
                    Cancel
                  </Button>
                  <Button
                    type="submit"
                    variant="contained"
                    color="primary"
                  >
                    Create Version
                  </Button>
                </Box>
              </Grid>
            </Grid>
          </form>
        </CardContent>
      </Card>
    </Box>
  );
};

export default CreateVersion;
